﻿namespace S4sme.Init
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using StructureMap;

    /// <summary>
    /// Taken from http://stevesmithblog.com/blog/how-do-i-use-structuremap-with-asp-net-mvc-3/
    /// </summary>
    public class StructureMapDependencyResolver : IDependencyResolver
    {
        /// <summary>
        /// Hold the container object
        /// </summary>
        private readonly IContainer container;

        /// <summary>
        /// Initializes a new instance of the <see cref="StructureMapDependencyResolver"/> class.
        /// </summary>
        /// <param name="container">
        /// The container.
        /// </param>
        public StructureMapDependencyResolver(IContainer container) 
        {
            this.container = container;
        }

        /// <summary>
        /// Get service type
        /// </summary>
        /// <param name="serviceType">
        /// The service type.
        /// </param>
        /// <returns>
        /// Instance of service
        /// </returns>
        public object GetService(Type serviceType)
        {
            if (serviceType.IsAbstract || serviceType.IsInterface) 
            {
                return this.container.TryGetInstance(serviceType);
            }
            
            return this.container.GetInstance(serviceType);
        }

        /// <summary>
        /// Get list of services
        /// </summary>
        /// <param name="serviceType">
        /// The service type.
        /// </param>
        /// <returns>
        /// list of services as IEnumerable
        /// </returns>
        public IEnumerable<object> GetServices(Type serviceType) 
        {
            return this.container.GetAllInstances(serviceType).Cast<object>();
        }
    }
}